package longrise.phone.com.bjjt_jyb.Utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.Time;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import Decoder.BASE64Encoder;
import longrise.phone.com.bjjt_jyb.R;


/**
 * Created by Administrator on 2016/5/13.
 */
public class CommontUtils {
    public static SimpleDateFormat dateSimple = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    private static final String CARVIN = "^[a-zA-Z0-9]{17}$"; // 车架VIN正则
    /**
     * 获取bitmap的大小
     */
    @SuppressLint("NewApi")
    public static int getBitmapSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // API 19
            return bitmap.getAllocationByteCount();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            // API 12
            return bitmap.getByteCount();
        }
        return bitmap.getRowBytes() * bitmap.getHeight(); // earlier version
    }

    // bitmap转byte[]
    public static byte[] BitmaptoBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        return baos.toByteArray();
    }

    public static String encodeBase64File(String path){
        File file = new File(path);
        byte[] buffer = null;
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BASE64Encoder().encode(buffer);
    }

    /**
     * Bitmap 转化为序列化的字符
     */
    public static String Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return com.longrise.LEAP.Base.IO.JSONSerializer.getInstance()
                .Serialize(baos.toByteArray());
    }

    /**
     * 返回系统当前时间 :xxxx年xx月xx日 hh:mm:ss
     *
     * @return
     */
    public static String getNowTime() {
        try {
            return dateSimple.format(new Date()) + "";
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 改变部分字体的颜色
     *
     * @param text：字符串
     * @param strs：变色的字符集合
     * @param colors：颜色的集合
     * @return
     */
    public static CharSequence changeStrColor(String text, String[] strs, int[] colors) {
        if (strs.length > colors.length) {
            return text;
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        for (int i = 0; i < strs.length; i++) {
            int color = colors[i];
            String indexStr = strs[i];
            int start = text.indexOf(indexStr);
            int end = start + indexStr.length();
            builder.setSpan(new ForegroundColorSpan(color), start, end,
                    Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return builder;
    }

    /**
     * 改变部分字体的颜色
     *
     * @param text：字符串
     * @param indexStr：变色的字符
     * @param color：变色的字符颜色
     * @return
     */
    public static CharSequence changeStrColor(String text, String indexStr, Integer color) {
        if (null == text || null == indexStr) {
            return text;
        }
        int start = text.indexOf(indexStr);
        if (start < 0) {
            return text;
        }
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        int end = start + indexStr.length();
        builder.setSpan(new ForegroundColorSpan(color), start, end,
                Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        return builder;
    }

    /**
     * 获取责任类型
     *
     * @param duty
     * @return
     */
    public static String getDutyStr(String duty) {
        if (TextUtils.equals(duty, "0")) {
            return "全责";
        } else if (TextUtils.equals(duty, "1")) {
            return "无责";
        } else if (TextUtils.equals(duty, "2")) {
            return "同责";
        }else if (TextUtils.equals(duty, "3")) {
            return "主责";
        }else if (TextUtils.equals(duty, "4")) {
            return "次责";
        }
        return "未知";
    }

    /**
     * 读取资源中的大图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitmap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 设置密码是否是明文
     */
    public static void setSeePwd(EditText editText,ImageView image) {
        if (editText != null) {
            TransformationMethod method = editText.getTransformationMethod();
            if (method instanceof PasswordTransformationMethod) {
                //可见
                image.setBackgroundResource(R.mipmap.a_93);
                editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                //隐藏
                image.setBackgroundResource(R.mipmap.a_62);
                editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            //移动光标到末尾
            editText.setSelection(editText.getText().toString().length());
        }
    }

    private static DisplayImageOptions options;

    //实例化imageloader的参数
    public static DisplayImageOptions getOptions() {
        if (null == options) {
            DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
            builder.showImageForEmptyUri(R.mipmap.download_fail1);
            builder.showImageOnFail(R.mipmap.download_fail);
            builder.showImageOnLoading(R.mipmap.reflash);
            builder.cacheInMemory(false);
            builder.cacheOnDisk(true);
            builder.imageScaleType(ImageScaleType.EXACTLY_STRETCHED);
            options = builder.build();
        }
        return options;
    }

    /**
     * 获取视频第一帧的图片
     * @param file
     * @return
     */
    public static Bitmap getVideoBitmap(String file){
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        //mmr.setDataSource("/sdcard/33.mp4");
        mmr.setDataSource(file);
        Bitmap bitmap = mmr.getFrameAtTime();
        mmr.release();
        return bitmap;
    }
    /**
     * 判断当前系统时间是否在指定时间的范围内
     *
     * @param beginHour
     *            开始小时，例如22
     * @param beginMin
     *            开始小时的分钟数，例如30
     * @param endHour
     *            结束小时，例如 8
     * @param endMin
     *            结束小时的分钟数，例如0
     * @return true表示在范围内，否则false
     */
    public static boolean isCurrentInTimeScope(int beginHour, int beginMin, int endHour, int endMin) {
        boolean result = false;
        final long aDayInMillis = 1000 * 60 * 60 * 24;
        final long currentTimeMillis = System.currentTimeMillis();

        Time now = new Time();
        now.set(currentTimeMillis);

        Time startTime = new Time();
        startTime.set(currentTimeMillis);
        startTime.hour = beginHour;
        startTime.minute = beginMin;

        Time endTime = new Time();
        endTime.set(currentTimeMillis);
        endTime.hour = endHour;
        endTime.minute = endMin;

        if (!startTime.before(endTime)) {
            // 跨天的特殊情况（比如22:00-8:00）
            startTime.set(startTime.toMillis(true) - aDayInMillis);
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
            Time startTimeInThisDay = new Time();
            startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);
            if (!now.before(startTimeInThisDay)) {
                result = true;
            }
        } else {
            // 普通情况(比如 8:00 - 14:00)
            result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime
        }
        return result;
    }
    public static boolean isCarvin(String carvin) {
        if (TextUtils.isEmpty(carvin)) {
            return false;
        }
        return Pattern.compile(CARVIN).matcher(carvin).matches();
    }

    public static Bitmap createPhotos(Bitmap bitmap){
        if(bitmap!=null){
            Matrix m=new Matrix();
            try{
                m.setRotate(90, bitmap.getWidth()/2, bitmap.getHeight()/2);//90就是我们需要选择的90度
                Bitmap bmp2=Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
                bitmap=bmp2;
            }catch(Exception ex){
                System.out.print("创建图片失败！"+ex);
            }
        }
        return bitmap;
    }

    // 获取bitmap的宽高，将宽度设为640，高度以倍数缩小，然后设置到bitmap中

    /**
     * 压缩图片文件，回传文件路径
     * @return
     */
    public static String bitmapNewWaH(String bImage ,Context context) {
        Bitmap imgeBitmap2 = BitmapFactory.decodeFile(bImage);
        int firstWidth = imgeBitmap2.getWidth();
        int firstHeight = imgeBitmap2.getHeight();
        //判断图片是竖屏还是横屏 获取新的宽高
        if(firstHeight>firstWidth){
            imgeBitmap2= CommontUtils.createPhotos(imgeBitmap2);
        }
        int oldWidth = imgeBitmap2.getWidth();
        int oldHeight = imgeBitmap2.getHeight();
        float times = (float)oldWidth / 640;
        int width = 640;
        float height = oldHeight / times;
        // 计算缩放比例
        // 计算缩放比例
        float scaleWidth = ((float) width) / oldWidth;
        float scaleHeight = height / oldHeight;
        // 想要缩放的宽高
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbitmap = Bitmap.createBitmap(imgeBitmap2, 0, 0, oldWidth, oldHeight, matrix, true);
        byte[] bytes = BitmaptoBytes(newbitmap);
        String path = SavePicturetoSdcard(bytes,context);
        return path;
    }

    // 保存相片到sdcard
    private static String SavePicturetoSdcard(byte[] data,Context context) {
        boolean success = false;
        try {
            if ((data != null) && (!data.equals("")) && (data.length > 0)) {
                String dir = FileUtils.getDir("KCKP", context);
                File file = new File(dir, FileUtils.dateformaterfilename());
                String absolutePath = file.getAbsolutePath();//照片的存储路径
                boolean writeFileissuccess = FileUtils.writeFile(data, absolutePath, false);// 将文件写入到SD卡下
                success = writeFileissuccess;
                return absolutePath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


